import { t } from 'i18next'
import {
	fetchChangeMicSpeakerVolume,
	fetchGetCheck,
	fetchGetMtDetail,
	fetchGetMtInfo,
	fetchGetMtInfoExt,
	fetchToggleMic,
	fetchToggleSpeaker,
	fetchCallChase,
} from '@/api/manager/mccMtInfo'
import {
	CallChaseParamsProps,
	ChangeMicSpeakerVolumeParamsProps,
	CheckInfoProps,
	GetMtDetailParamsProps,
	GetMtDetailReturnProps,
	GetMtInfoExtParamsProps,
	GetMtInfoExtReturnProps,
	GetMtInfoParamsProps,
	ToggleMicParamsProps,
	ToggleSpeakerParamsProps,
} from '@/api/manager/mccMtInfo/interface'
import Alert from '@/components/Alert'
import dayjs from '@/plugins/dayjs'
import { useEffect, useState } from 'react'
import { useMccStore } from '../../store'
import shallow from 'zustand/shallow'
import { CheckProps, MtInfoExtProps } from './interface'
import { ReSetNtfDataProps, useMccMtInfoStore } from './store'
import { useInterval } from 'ahooks'
import { getItemByMtKey } from '../main/table/all/utils'
import { useTableAllStore } from '../main/table/all/store'

const config = {
	/**最大音量 */
	MAX_volume: 31,
	MAX_bar_length: 93,
	ACK_source_isMt: 1,
	ACK_source_isVmp: 2,
	ACK_source_isMix: 3,
	ACK_source_noAutoCallMode: 0,
	ACK_source_autoCallMode: 2,
	ACK_source_isMix_desc: t('混音'),
	ACK_source_isVmp_desc: t('画面合成'),
	ACK_source_noAutoCallMode_desc: t('手动'),
	ACK_source_autoCallMode_desc: t('定时'),
}

const useHookData = () => {
	const { cometdMccMtInfo, mt, mtInfo, setMtInfo, mic, setMic, speaker, setSpeaker } = useMccMtInfoStore(
		(state) => ({
			cometdMccMtInfo: state.cometdMccMtInfo,
			mtInfo: state.mtInfo,
			mic: state.mic,
			speaker: state.speaker,
			mt: state.mt,
			setMtInfo: state.setMtInfo,
			setMic: state.setMic,
			setSpeaker: state.setSpeaker,
		}),
		shallow
	)
	/**音频 */
	const [audioFrequency, setAudioFrequency] = useState<string>('')
	/**音频源 */
	const [mtInfoExt, setMtInfoExt] = useState<MtInfoExtProps>({
		/**音频源 */
		videoSource: '',
		/**视频源 */
		radioSource: '',
		/**呼叫方式 */
		callMethod: '',
		/**呼叫间隔  */
		callInterval: 0,
		/**呼叫次数  */
		callTime: '',
		/**是否展示呼叫间隔 默认隐藏*/
		isShowCallInterval: false,
		/**是否展示呼叫次数  默认隐藏*/
		isShowCallTime: false,
		/**呼叫模式 */
		callMode: 0,
		/**追呼 开启 关闭 */
		callChase: false,
	})
	const [mtDetail, setMtDetail] = useState<GetMtDetailReturnProps>()
	/**终端检测的结果 以及 展示终端检测的具体详细信息：发生时间、异常问题、解决方案等 */
	const [check, setCheck] = useState<CheckProps>({
		status: '', //abnormal:异常
		text: '',
		isShowCheckStatusText: false,
		suggestion: '',
		eventTime: '',
		description: '',
		isShowCheckDetailInfo: false,
	})
	const isSubMtOffline = mt.isMt && !mt.mtid && mt.confLevel !== 2 /**下级离线终端*/
	/** 初始化页面进来时 是否展示一下项*/
	const showByMtWhenInit = {
		/**是否展示 呼叫协议 */
		isShowProtocol: !isSubMtOffline && mt.isMt,
		/**是否展示 追呼 */
		isShowCallChase: !isSubMtOffline && mt.isMt,
		/**是否展示 终端接收丢包率 内容 */
		isShowTerminalReceivingPacketLossRate: !isSubMtOffline && mt.isMt,
		/**是否展示 终端发送丢包率 内容 */
		isShowTerminalSendingPacketLossRate: !isSubMtOffline && mt.isMt,
		/**是否展示 呼叫信息标题 */
		isShowCallInfoTitle: !isSubMtOffline && mt.isMt,
		/**是否展示 终端发送/接收 标题*/
		isShowTerminalSendingReceivingTitle: !isSubMtOffline && mt.isMt,
		/**是否展示 终端检测 和后面的检测结果*/
		isShowTerminalCheckTitleAndStatusText: !isSubMtOffline && mt.isMt,
	}
	//每5秒获取一次终端信息
	useInterval(() => {
		if (!isSubMtOffline) {
			getMtInfo()
			getChecking()
		}
	}, 5000)
	useEffect(() => {
		if (!isSubMtOffline) {
			getMtInfo()
			getChecking()
		}
	}, [mt])
	useEffect(() => {
		if (!isSubMtOffline) {
			cometdMccMtInfo && reSetNtfByCometdMccMtInfo(cometdMccMtInfo)
		}
	}, [cometdMccMtInfo])
	/**获取终端信息 */
	const getMtInfo = () => {
		let mt_id = mt.mtid
		if (mt.confLevel === 1) {
			//是上级会议
			let mtids = mt.mtid.split(/[\._]/)
			mt_id = mtids[mtids.length - 1]
		}
		let para: GetMtInfoParamsProps = {
			mt_id: mt_id,
			interactive_mt: mt.interactiveMt,
		}
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		fetchGetMtInfo(para, meetingMoid).then((data) => {
			setMtInfo(data)
			if (data) {
				setMic({
					isMute: data.mute,
				})
				setSpeaker({
					isSilence: data.silence,
				})
				if (mt.mtid.indexOf('_') !== -1) {
					getMtInfoExt()
					//下级终端
					return
				}
				/**初始化 麦克风和扬声器 的初始值 */
				setViewMic(data.snd_volume || 0)
				setViewSpeaker(data.rcv_volume || 0)
				let info = {
					a_snd_chn: data.a_snd_chn || [],
					a_rcv_chn: data.a_rcv_chn || [],
				}
				updateAudioFrequency(info)
			}
			getMtInfoExt()
		})
	}
	/**	获取终端其他信息 */
	const getMtInfoExt = () => {
		let mt_id = mt.mtid
		let para: GetMtInfoExtParamsProps = {
			mt_id: mt_id,
			interactive_mt: mt.interactiveMt,
		}
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		fetchGetMtInfoExt(para, meetingMoid).then((data) => {
			getMtDetail()
			if (mt.mtid.indexOf('_') !== -1) {
				//下级终端
				return
			}
			reSetMtInfoExt(data)
		})
	}
	const reSetNtfByCometdMccMtInfo = (_cometdMccMtInfo: ReSetNtfDataProps) => {
		let videoSource: string | undefined = ''
		let radioSource: string | undefined = ''
		let callInfo = {}
		let data = _cometdMccMtInfo || {}
		if (!mt.mtid || data.mt?.mt_id !== mt.mtid) {
			return
		}
		if (mt.mtid.indexOf('_') !== -1) {
			//下级终端
			let par = { call_mode: data.call_mode, call_interval: data.call_interval, call_times: data.call_times }
			callInfo = updateCallInfo(par)
		} else {
			//本级终端
			return
		}
		//下级终端音视频源
		if (data.v_rcv_chn[0] && data.v_rcv_chn[0].src_type) {
			if (data.v_rcv_chn[0].src_type === 1) {
				radioSource = data.v_rcv_chn[0].src
			} else if (data.v_rcv_chn[0].src_type === 2) {
				radioSource = t('画面合成')
			} else if (data.v_rcv_chn[0].src_type === 3) {
				radioSource = t('混音')
			}
		}
		if (data.a_rcv_chn[0] && data.a_rcv_chn[0].src_type) {
			if (data.a_rcv_chn[0].src_type === 1) {
				//终端
				videoSource = data.a_rcv_chn[0].src
			} else if (data.a_rcv_chn[0].src_type === 2) {
				//画面合成
				videoSource = t('画面合成')
			} else if (data.a_rcv_chn[0].src_type === 3) {
				//混音
				videoSource = t('混音')
			}
		}
		setMtInfoExt((v) => ({
			...v,
			videoSource,
			radioSource,
			...callInfo,
		}))
		//下级终端音量
		let volume = 0
		if (data.a_snd_chn[0] && data.a_snd_chn[0].volume) {
			volume = data.a_snd_chn[0].volume
		}
		setViewMic(volume)
		var speakerVolume = 0
		if (data.a_rcv_chn[0] && data.a_rcv_chn[0].volume) {
			speakerVolume = data.a_rcv_chn[0].volume
		}
		setViewSpeaker(speakerVolume)
		let info = {
			a_snd_chn: data.a_snd_chn || [],
			a_rcv_chn: data.a_rcv_chn || [],
		}
		updateAudioFrequency(info)
	}
	/**	重置 终端其他信息 */
	const reSetMtInfoExt = (data?: GetMtInfoExtReturnProps) => {
		let mtName = '',
			mtid
		/**音频源 */
		let videoSource = '',
			/**视频源 */
			radioSource = ''
		if (data) {
			if (data.audio_rcv.length) {
				let first = data.audio_rcv[0]
				if (first.src.src_type === config.ACK_source_isMt) {
					mtid = first.src.mt_id
					let item = getItemByMtKey(useTableAllStore.getState().tree, mtid)
					mtName = item ? item.mcc.name : ''
					mtName = mtName.replace(/&nbsp;/g, ' ')
					videoSource = mtName
				} else if (first.src.src_type === config.ACK_source_isMix) {
					videoSource = config.ACK_source_isMix_desc
				} else if (first.src.src_type === config.ACK_source_noAutoCallMode) {
					videoSource = ''
				}
			}
			if (data.video_rcv.length) {
				let first = data.video_rcv[0]
				if (first.src.src_type === config.ACK_source_isMt) {
					mtid = first.src.mt_id
					let item = getItemByMtKey(useTableAllStore.getState().tree, mtid)
					mtName = item ? item.mcc.name : ''
					mtName = mtName.replace(/&nbsp;/g, ' ')
					radioSource = mtName
				} else if (first.src.src_type === config.ACK_source_isVmp) {
					radioSource = config.ACK_source_isVmp_desc
				} else if (first.src.src_type === config.ACK_source_noAutoCallMode) {
					radioSource = ''
				}
			}
			let par = { call_mode: data.call_mode, call_interval: data.call_interval, call_times: data.call_times }
			let callInfo = updateCallInfo(par)
			setMtInfoExt((v) => ({
				...v,
				videoSource,
				radioSource,
				callMode: data.call_mode,
				...callInfo,
			}))
		} else {
			setMtInfoExt((v) => ({ ...v, videoSource: '', radioSource: '' }))
		}
	}
	const updateCallInfo = (data: { call_mode: number; call_interval: number; call_times: number }) => {
		/**呼叫方式 */
		let callMethod = '',
			/**呼叫间隔  */
			callInterval = 0,
			/**呼叫次数  */
			callTime = '',
			/**是否展示呼叫间隔 */
			isShowCallInterval = false,
			/**是否展示呼叫次数 */
			isShowCallTime = false,
			/**追呼 */
			callChase = false
		if (data.call_mode === config.ACK_source_noAutoCallMode) {
			callMethod = t('手动呼叫')
			isShowCallInterval = false
			isShowCallTime = false
			callChase = false
		} else if (data.call_mode === config.ACK_source_autoCallMode) {
			callMethod = t('自动呼叫')
			callInterval = data.call_interval
			callTime = data.call_times === 0 ? t('不限次数') : String(data.call_times)
			isShowCallInterval = true
			isShowCallTime = true
			callChase = false
		} else if (data.call_mode === 9) {
			callMethod = t('手动呼叫')
			isShowCallInterval = false
			isShowCallTime = false
			callChase = true
		} else if (data.call_mode === 10) {
			callMethod = t('自动呼叫')
			callInterval = data.call_interval
			callTime = data.call_times === 0 ? t('不限次数') : String(data.call_times)
			isShowCallInterval = true
			isShowCallTime = true
			callChase = true
		}
		return {
			callMethod,
			callInterval,
			callTime,
			isShowCallInterval,
			isShowCallTime,
			callChase,
		}
	}
	const getMtDetail = () => {
		var mt_id = mt.mtid
		if (mt.confLevel === 1) {
			//是上级会议
			var mtids = mt.mtid.split(/[\._]/)
			mt_id = mtids[mtids.length - 1]
		}
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		let para: GetMtDetailParamsProps = {
			meeting_moid: meetingMoid,
			mt_id: mt_id,
			interactive_mt: mt.interactiveMt,
		}
		fetchGetMtDetail(para).then((data) => {
			setMtDetail(data)
		})
	}
	/**终端检测 */
	const getChecking = () => {
		const enableJdb = useMccStore.getState().enableJdb
		if (!enableJdb) {
			setCheck((v) => ({
				...v,
				isShowCheckStatusText: false,
				isShowCheckDetailInfo: false,
			}))
			return
		}
		let meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		let e164 = mt.e164
		fetchGetCheck(meetingMoid, e164).then((data) => {
			if (data) {
				if (data.length === 0) {
					setCheck((v) => ({
						...v,
						text: t('音视频正常'),
						isShowCheckStatusText: true,
						isShowCheckDetailInfo: false,
					}))
				} else {
					let item: CheckInfoProps = data.reduce((prev: CheckInfoProps, cur) => {
						if (prev.event_time) {
							if (new Date(prev.event_time).getTime() > new Date(cur.event_time).getTime()) {
								return prev
							} else {
								return cur
							}
						} else {
							return cur
						}
					})
					setCheck((v) => ({
						...v,
						text: t('异常'),
						status: 'abnormal',
						isShowCheckStatusText: true,
						suggestion: item.suggestion,
						eventTime: dayjs(item.event_time).format('YYYY-MM-DD HH:mm:ss'),
						description: item.description || '',
						isShowCheckDetailInfo: true,
					}))
				}
			} else {
				setCheck((v) => ({
					...v,
					isShowCheckStatusText: false,
					isShowCheckDetailInfo: false,
				}))
			}
		})
	}
	/**追呼 */
	const onCallChaseChange = (v: boolean) => {
		let meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		let para: CallChaseParamsProps
		let mode = null
		if (v) {
			//开
			para = {
				meeting_moid: meetingMoid,
				value: '3',
				mt: {
					e164: mtInfo?.e164 || '',
					mt_id: mtInfo?.mt_id || '',
					mt_ip: mtInfo?.mt_ip || '',
					mt_key: mtInfo?.mt_key || '',
					name: mtInfo?.name || '',
					conf_e164: mtInfo?.conf_e164 || '',
					account: mtInfo?.account || '',
					stream: mtInfo?.stream || 0,
					online: mtInfo?.online || 0,
					account_type: mtInfo?.account_type,
					bitrate: mtInfo?.bitrate || 0,
					mt_type: mtInfo?.mt_type,
				},
			}
		} else {
			if (mtInfoExt.callMode === 9) {
				//手动加追呼
				mode = 0
			} else if (mtInfoExt.callMode === 10) {
				//自动加追呼
				mode = 2
			} else {
				mode = mtInfoExt.callMode
			}
			para = {
				meeting_moid: meetingMoid,
				value: String(mode),
				mt: {
					e164: mtInfo?.e164 || '',
					mt_id: mtInfo?.mt_id || '',
					mt_ip: mtInfo?.mt_ip || '',
					mt_key: mtInfo?.mt_key || '',
					name: mtInfo?.name || '',
					conf_e164: mtInfo?.conf_e164 || '',
					account: mtInfo?.account || '',
					stream: mtInfo?.stream || 0,
					online: mtInfo?.online || 0,
					account_type: mtInfo?.account_type,
					bitrate: mtInfo?.bitrate || 0,
					mt_type: mtInfo?.mt_type,
				},
			}
		}
		fetchCallChase(para).then((res) => {
			if (!res) {
				Alert(t('开启追呼失败'))
			}
			if (res) {
				setMtInfoExt((prev) => ({
					...prev,
					callChase: v,
				}))
			}
		})
	}
	/**调节麦克风 音量*/
	const setViewMic = (volume: number) => {
		if (volume > config.MAX_volume) {
			volume = config.MAX_volume
		}
		var percent = Math.floor((volume / config.MAX_volume) * 100)
		setMic({
			value: percent,
		})
	}
	/**调节扬声器 音量*/
	const setViewSpeaker = (volume: number) => {
		if (volume > config.MAX_volume) {
			volume = config.MAX_volume
		}
		var percent = Math.floor((volume / config.MAX_volume) * 100)
		setSpeaker({
			value: percent,
		})
	}
	/**切换麦克风的 取消哑音0 设置哑音1 */
	const onToggleMicBtn = (value: 0 | 1) => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		let para: ToggleMicParamsProps = {
			meeting_moid: meetingMoid,
			value: value,
			mts: [
				{
					mt_id: mtInfo?.mt_id || '',
					mt_ip: mtInfo?.mt_ip || '',
					mt_key: mtInfo?.mt_key || '',
					name: mtInfo?.name || '',
					account: mtInfo?.account || '',
					account_type: mtInfo?.account_type,
					conf_e164: mtInfo?.conf_e164 || '',
					protocol: mtInfo?.protocol || '',
				},
			],
		}
		fetchToggleMic(para).then((res) => {
			if (!res) {
				Alert(value ? t('设置哑音失败') : t('取消哑音失败'))
				return
			}
			setMic({
				isMute: mic.isMute === 1 ? 0 : 1,
			})
		})
	}
	/**切换扬声器的 取消静音0 设置静音1 */
	const onToggleSpeakerBtn = (value: 0 | 1) => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		let para: ToggleSpeakerParamsProps = {
			meeting_moid: meetingMoid,
			mt_id: mt.mtid,
			value: value,
			mts: [
				{
					mt_id: mtInfo?.mt_id || '',
					mt_ip: mtInfo?.mt_ip || '',
					mt_key: mtInfo?.mt_key || '',
					name: mtInfo?.name || '',
					account: mtInfo?.account || '',
					account_type: mtInfo?.account_type,
					conf_e164: mtInfo?.conf_e164 || '',
					protocol: mtInfo?.protocol || '',
				},
			],
		}
		fetchToggleSpeaker(para).then((res) => {
			if (!res) {
				Alert(value ? t('设置静音失败') : t('取消静音失败'))
				return
			}
			setSpeaker({
				isSilence: speaker.isSilence === 1 ? 0 : 1,
			})
		})
	}
	/**滑动时 麦克风或者扬声器的音量 */
	const onSliderChange = (value: number, keyName: string) => {
		if (keyName === 'micValue') {
			setMic({
				changeValue: value,
			})
		} else {
			setSpeaker({
				changeValue: value,
			})
		}
	}
	/**点击、滑动调节结束时 麦克风或者扬声器的音量 */
	const onSliderChangeEnd = (value: number, keyName: string) => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		let volume = Math.ceil((value / 100) * config.MAX_volume)
		let para: ChangeMicSpeakerVolumeParamsProps = {
			meeting_moid: meetingMoid,
			mt_id: mt.mtid,
			vol_value: volume,
			vol_mode: keyName === 'micValue' ? 2 : 1,
			mt: {
				mt_id: mtInfo?.mt_id || '',
				mt_ip: mtInfo?.mt_ip || '',
				mt_key: mtInfo?.mt_key || '',
				name: mtInfo?.name || '',
				account: mtInfo?.account || '',
				account_type: mtInfo?.account_type,
				conf_e164: mtInfo?.conf_e164 || '',
				protocol: mtInfo?.protocol || '',
			},
		}
		fetchChangeMicSpeakerVolume(para)
			.then((res) => {
				if (!res) {
					Alert(t('调节音量失败'))
					return
				}
				if (keyName === 'micValue') {
					setMic({
						value: value,
						changeValue: 0,
					})
				} else {
					setSpeaker({
						value: value,
						changeValue: 0,
					})
				}
			})
			.catch(() => {
				setMic({
					changeValue: 0,
				})
				setSpeaker({
					changeValue: 0,
				})
			})
	}
	/**音频的展示 */
	const updateAudioFrequency = (info: { a_snd_chn: any[]; a_rcv_chn: any[] }) => {
		let s = ''
		if (info) {
			if (info.a_snd_chn.length > 0 && info.a_rcv_chn.length > 0) {
				s = t('发送中/接收中')
			} else if (info?.a_snd_chn.length === 0 && info?.a_rcv_chn.length > 0) {
				s = t('未发送/接收中')
			} else if (info?.a_snd_chn.length === 0 && info?.a_rcv_chn.length === 0) {
				s = t('未发送/未接收')
			} else if (info?.a_snd_chn.length > 0 && info?.a_rcv_chn.length === 0) {
				s = t('发送中/未接收')
			}
		}
		setAudioFrequency(s)
	}
	return {
		mtInfo,
		check,
		onCallChaseChange,
		onSliderChangeEnd,
		config,
		onSliderChange,
		audioFrequency,
		mtDetail,
		/**切换麦克风的 取消哑音 设置哑音 */
		onToggleMicBtn,
		/**切换扬声器的 取消静音 设置静音 */
		onToggleSpeakerBtn,
		/**终端其他信息 */
		mtInfoExt,
		mt,
		showByMtWhenInit,
		/**麦克风 */
		mic,
		/**扬声器 */
		speaker,
		cometdMccMtInfo,
		isSubMtOffline,
	}
}
export default useHookData
